"use client"

import { Book, Database as DatabaseIcon, Users } from "lucide-react"
import { useState, useEffect } from "react"
import { usePathname, useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import {
  ChevronLeft,
  ChevronRight,
  ChevronDown,
  ChevronUp,
  Zap,
  Wind,
  Wrench,
  Radio,
  Gauge,
  FileSpreadsheet,
  Database,
  BarChart3,
  Ruler,
  LogOut,
} from "lucide-react"
import { cn } from "@/lib/utils"
import Link from "next/link"
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible"
import { UserAvatar } from "@/components/user-avatar"

interface SidebarProps {
  className?: string
  dataCounts?: {
    piping?: number
    electrical?: number
    hvac?: number
    communication?: number
    instrumentation?: number
  }
}

export function Sidebar({ className, dataCounts }: SidebarProps) {
  const pathname = usePathname()
  const router = useRouter()
  const [isCollapsed, setIsCollapsed] = useState(false)
  const [isStandardsExpanded, setIsStandardsExpanded] = useState(false)
  const [activeItem, setActiveItem] = useState("dashboard") // 默认激活Dashboard
  const [currentUserRole, setCurrentUserRole] = useState<string | null>(null)

  // 根据当前路径确定激活的菜单项
  useEffect(() => {
    if (pathname === "/") {
      setActiveItem("dashboard")
    } else if (pathname.startsWith("/piping")) {
      setActiveItem("piping")
    } else if (pathname.startsWith("/electrical")) {
      setActiveItem("electrical")
    } else if (pathname.startsWith("/hvac")) {
      setActiveItem("hvac")
    } else if (pathname.startsWith("/communication")) {
      setActiveItem("communication")
    } else if (pathname.startsWith("/instrumentation")) {
      setActiveItem("instrumentation")

    } else if (pathname.startsWith("/excel-analysis")) {
      setActiveItem("excel-analysis")
      setIsStandardsExpanded(true)
    } else if (pathname.startsWith("/data-import")) {
      setActiveItem("data-import")
      setIsStandardsExpanded(true)
    } else if (pathname.startsWith("/measurement-units")) {
      setActiveItem("measurement-units")
      setIsStandardsExpanded(true)
    } else if (pathname.startsWith("/excel-viewer")) {
      setActiveItem("excel-viewer")
    } else if (pathname.startsWith("/template-manager")) {
      setActiveItem("template-manager")
    }
  }, [pathname])

  useEffect(() => {
    // 延迟检查，确保客户端渲染完成
    const checkUser = () => {
      const userStr = typeof window !== 'undefined' ? localStorage.getItem("currentUser") : null;
      if (userStr) {
        try {
          const user = JSON.parse(userStr);
          setCurrentUserRole(user.role);
        } catch {
          setCurrentUserRole(null);
        }
      } else {
        setCurrentUserRole(null);
        // 只在客户端且不在登录页面时重定向
        if (typeof window !== 'undefined' && !window.location.pathname.includes('/login')) {
          router.push("/login");
        }
      }
    };

    // 延迟执行，确保组件完全挂载
    const timer = setTimeout(checkUser, 100);
    return () => clearTimeout(timer);
  }, [router]);

  const specialties = [
    {
      id: "piping",
      name: "配管专业",
      icon: Wrench,
      count: dataCounts?.piping || 0,
      href: "/piping",
    },
    {
      id: "electrical",
      name: "电气专业",
      icon: Zap,
      count: dataCounts?.electrical || 0,
      href: "/electrical",
    },
    {
      id: "hvac",
      name: "暖通专业",
      icon: Wind,
      count: dataCounts?.hvac || 0,
      href: "/hvac",
    },
    {
      id: "communication",
      name: "通信专业",
      icon: Radio,
      count: dataCounts?.communication || 0,
      href: "/communication",
    },
    {
      id: "instrumentation",
      name: "仪表专业",
      icon: Gauge,
      count: dataCounts?.instrumentation || 0,
      href: "/instrumentation",
    },
  ]

  // 计算总量
  const totalCount = (dataCounts?.piping || 0) +
                    (dataCounts?.electrical || 0) +
                    (dataCounts?.hvac || 0) +
                    (dataCounts?.communication || 0) +
                    (dataCounts?.instrumentation || 0)

  return (
    <div
      className={cn(
        "relative flex flex-col border-r bg-white transition-all duration-300",
        isCollapsed ? "w-16" : "w-64",
        className,
      )}
    >
      {/* Header */}
      <div className="border-b">
        {/* User Avatar Section */}
        <div className="flex h-16 items-center justify-between px-4">
          {!isCollapsed && (
            <div className="flex-1 mr-2">
              <UserAvatar />
            </div>
          )}
          {isCollapsed && (
            <div className="flex justify-center w-full">
              <UserAvatar />
            </div>
          )}
          {!isCollapsed && (
            <Button variant="ghost" size="sm" onClick={() => setIsCollapsed(!isCollapsed)} className="h-8 w-8 p-0">
              <ChevronLeft className="h-4 w-4" />
            </Button>
          )}
        </div>

        {/* Navigation Title */}
        {!isCollapsed && (
          <div className="px-4 pb-3">
            <h2 className="text-sm font-medium text-gray-600">导航菜单</h2>
          </div>
        )}

        {/* Collapse Button for collapsed state */}
        {isCollapsed && (
          <div className="flex justify-center pb-2">
            <Button variant="ghost" size="sm" onClick={() => setIsCollapsed(!isCollapsed)} className="h-8 w-8 p-0">
              <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        )}
      </div>

      {/* Navigation */}
      <nav className="flex-1 space-y-1 p-2">
        {/* Dashboard */}
        <Link href="/" className="block">
          <Button
            variant={activeItem === "dashboard" ? "default" : "ghost"}
            className={cn(
              "w-full justify-start gap-3 h-12 transition-all duration-200",
              activeItem === "dashboard" && "bg-primary text-white shadow-md",
              activeItem !== "dashboard" && "hover:bg-primary/10 hover:text-primary",
              isCollapsed && "justify-center px-2",
            )}
          >
            <BarChart3 className="h-5 w-5 flex-shrink-0" />
            {!isCollapsed && (
              <>
                <span className="flex-1 text-left font-medium">数据中台</span>
                {totalCount > 0 && (
                  <Badge
                    variant={activeItem === "dashboard" ? "secondary" : "outline"}
                    className={cn(
                      "ml-auto transition-all duration-200",
                      activeItem === "dashboard" && "bg-white/20 text-white border-white/30",
                      activeItem !== "dashboard" && "border-primary/20 text-primary/70",
                    )}
                  >
                    {totalCount}
                  </Badge>
                )}
              </>
            )}
          </Button>
        </Link>

        {/* 专业分隔线 */}
        {!isCollapsed && (
          <div className="px-2 py-2">
            <div className="border-t border-gray-200"></div>
            <p className="text-xs text-gray-500 mt-2 px-2">专业管理</p>
          </div>
        )}

        {specialties.map((specialty) => {
          const Icon = specialty.icon
          const isActive = activeItem === specialty.id
          return (
            <Link key={specialty.id} href={specialty.href} className="block">
              <Button
                variant={isActive ? "default" : "ghost"}
                className={cn(
                  "w-full justify-start gap-3 h-12 transition-all duration-200",
                  isActive && "bg-primary text-white shadow-md",
                  !isActive && "hover:bg-primary/10 hover:text-primary",
                  isCollapsed && "justify-center px-2",
                )}
              >
                <Icon className="h-5 w-5 flex-shrink-0" />
                {!isCollapsed && (
                  <>
                    <span className="flex-1 text-left font-medium">{specialty.name}</span>
                    {specialty.count > 0 && (
                      <Badge
                        variant={isActive ? "secondary" : "outline"}
                        className={cn(
                          "ml-auto transition-all duration-200",
                          isActive && "bg-white/20 text-white border-white/30",
                          !isActive && "border-primary/20 text-primary/70",
                        )}
                      >
                        {specialty.count}
                      </Badge>
                    )}
                  </>
                )}
              </Button>
            </Link>
          )
        })}

        {/* 规范管理分隔线 */}
        {!isCollapsed && currentUserRole === "admin" && (
          <div className="px-2 py-2">
            <div className="border-t border-gray-200"></div>
          </div>
        )}

        {/* 规范管理，仅管理员可见 */}
        {currentUserRole === "admin" && (
          <Collapsible open={isStandardsExpanded} onOpenChange={setIsStandardsExpanded}>
            <CollapsibleTrigger asChild>
              <Button
                variant={isStandardsExpanded ? "secondary" : "ghost"}
                className={cn(
                  "w-full justify-start text-left",
                  isCollapsed && "justify-center",
                  isStandardsExpanded && "bg-muted font-semibold"
                )}
              >
                <Book className="h-4 w-4" />
                {!isCollapsed && <span className="ml-2 flex-1">规范管理</span>}
                {!isCollapsed && (isStandardsExpanded ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />)}
              </Button>
            </CollapsibleTrigger>
            <CollapsibleContent className="space-y-1 pt-1">
              <Link href="/excel-analysis">
                <Button variant={activeItem === "excel-analysis" ? "default" : "ghost"} size="sm" className="w-full justify-start pl-8">
                  属性表
                </Button>
              </Link>
              <Link href="/equipment-table">
                <Button variant={activeItem === "equipment-table" ? "default" : "ghost"} size="sm" className="w-full justify-start pl-8">
                  设备表
                </Button>
              </Link>
              <Link href="/measurement-units">
                <Button variant={activeItem === "measurement-units" ? "default" : "ghost"} size="sm" className="w-full justify-start pl-8">
                  计量单位定义表
                </Button>
              </Link>
            </CollapsibleContent>
          </Collapsible>
        )}

        {/* sqlite管理，仅管理员可见，显示在用户管理前 */}
        {/*
        {currentUserRole === "admin" && (
          <Link href="/sqlite-management" className="block">
            <Button
              variant={activeItem === "sqlite-management" ? "default" : "ghost"}
              className={cn(
                "w-full justify-start gap-3 h-12 transition-all duration-200",
                activeItem === "sqlite-management" && "bg-primary text-white shadow-md",
                activeItem !== "sqlite-management" && "hover:bg-primary/10 hover:text-primary",
                isCollapsed && "justify-center px-2",
              )}
            >
              <Database className="h-5 w-5 flex-shrink-0" />
              {!isCollapsed && <span className="flex-1 text-left font-medium">sqlite管理</span>}
            </Button>
          </Link>
        )}
        */}

        {/* 模板管理分隔线 */}
        {!isCollapsed && (
          <div className="px-2 py-2">
            <div className="border-t border-gray-200"></div>
          </div>
        )}

        {/* 模板管理 */}
        <Link href="/template-manager" className="block">
          <Button
            variant={activeItem === "template-manager" ? "default" : "ghost"}
            className={cn(
              "w-full justify-start gap-3 h-12 transition-all duration-200",
              activeItem === "template-manager" && "bg-primary text-white shadow-md",
              activeItem !== "template-manager" && "hover:bg-primary/10 hover:text-primary",
              isCollapsed && "justify-center px-2",
            )}
          >
            <FileSpreadsheet className="h-5 w-5 flex-shrink-0" />
            {!isCollapsed && <span className="flex-1 text-left font-medium">模板管理</span>}
          </Button>
        </Link>

        {/* 用户管理，仅管理员可见 */}
        {currentUserRole === "admin" && (
          <Link href="/user-management" className="block">
            <Button
              variant={activeItem === "user-management" ? "default" : "ghost"}
              className={cn(
                "w-full justify-start gap-3 h-12 transition-all duration-200",
                activeItem === "user-management" && "bg-primary text-white shadow-md",
                activeItem !== "user-management" && "hover:bg-primary/10 hover:text-primary",
                isCollapsed && "justify-center px-2",
              )}
            >
              <Users className="h-5 w-5 flex-shrink-0" />
              {!isCollapsed && <span className="flex-1 text-left font-medium">用户管理</span>}
            </Button>
          </Link>
        )}
      </nav>
      {/* 登出按钮 */}
      <div className="border-t p-2">
        <Button
          variant="ghost"
          className="w-full justify-start gap-3 h-12 text-red-600 hover:bg-red-50 hover:text-red-700"
          onClick={() => {
            localStorage.removeItem("currentUser");
            router.push("/login");
          }}
        >
          <LogOut className="h-5 w-5 flex-shrink-0" />
          {!isCollapsed && <span className="flex-1 text-left font-medium">登出</span>}
        </Button>
      </div>
    </div>
  )
}
